<template>
  <div v-if="rawData">
    <div class="h12" />
    <el-card>
      <div slot="header" class="clearfix flex">
        <b>趋势分析</b>
        <div class="search-container">
          <el-date-picker
            v-model="timetran"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
          <el-button type="primary" class="btn" @click="search">查询</el-button>
        </div>
      </div>
      <div class="trend-container">
        <ve-line v-if="chartData && chartData.categories && chartData.categories.length > 0" :data="chartData" :settings="chartSettings" />
        <el-empty v-else description="暂无任何趋势分析数据" />
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getAll } from '@/api/statistics'
export default {
  props: {
    cserialno: {
      type: String,
      default() {
        return ''
      }
    },
    activeName: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      timetran: '',
      listQuery: { day: 1 },
      rawData: null,
      chartData: null,
      chartSettings: {}
    }
  },
  computed: {
    ...mapGetters(['currentDevice', 'currentDeviceShow'])
  },
  watch: {
    currentDeviceShow: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.getStatistics(this.listQuery)
        }
      },
      deep: true,
      immediate: true
    },
    activeName(newVal, oldVal) {
      this.search()
    }
  },
  methods: {
    search() {
      this.getStatistics({ timetran: this.timetran })
    },
    async getStatistics(params) {
      Object.assign(this.listQuery, { serialno: this.currentDevice.serialno, cserialno: this.cserialno }, params)
      const { data } = await getAll(this.listQuery)
      this.rawData = data
      this.chartData = this.formatStatistics(data.categories, data.series)
      this.chartSettings = data.chartSettings
    },
    formatStatistics(categories, series) {
      const columns = ['日期']; const rows = []
      for (let i = 0; i < categories.length; i++) {
        const item = { '日期': categories[i] }
        for (const citem of series) {
          item[citem.name] = citem.data[i]
          if (i === 0) {
            columns.push(citem.name)
          }
        }
        rows.push(item)
      }
      return {
        columns: columns,
        rows: rows
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.flex{
  align-items: center;
}
.search-container{
  margin-left:auto;
  .btn{
    margin-left:12px;
  }
}
</style>
